<?php
namespace app\common\model;
use think\facade\Cache;
use think\Model;

class ArticleAttribute extends Model
{

    public function getTitleAttr($value){
        return html_entity_decode($value);
    }
    public function getContentAttr($value){
        return html_entity_decode($value);
    }
    static function onAfterInsert(Model $model)
    {
        if (Cache::has('carouselArticle')) {
            Cache::delete('carouselArticle');
        }
        if (Cache::has('newArticle')) {
            Cache::delete('newArticle');
        }
    }

    static function onAfterUpdate(Model $model)
    {
        $cacheName = 'article_' . $model->article_id;
        if (Cache::has($cacheName)) {
            Cache::delete($cacheName);
        }
        if (Cache::has('carouselArticle')) {
            Cache::delete('carouselArticle');
        }
        if (Cache::has('newArticle')) {
            Cache::delete('newArticle');
        }
    }

    public function getJsonData($name,$where=[]){
        //最新数据
        switch ($name){
            case 'viewtop':
                $field=$where['field'];
                $limit=$where['limit'];
                $list = (new Article())
                    ->where('status',1)
                    ->order($field, 'desc')
                    ->limit($limit)
                    ->column('id,title,category_id,keywords,description,cover_img,publish_time');
                $categorys=getJsonData('ArticleCategory','list');
                $cate=array_column($categorys,'alias','id');
                foreach ($list as &$v){
                    $v['url']=Article::detailUrl($v['id'],$v['category_id'],$cate);
                }
                return $list;
                break;
        }
    }

    static function lift($id)
    {
        $model=new Article();
        $categorys = getJsonData('ArticleCategory', 'list');
        $cate = array_column($categorys, 'alias', 'id');

        $lift['prev'] = $model->where('id','<',$id)->where('status',1)->order('id','desc')->find();
        if ($lift['prev']) {
            $lift['prev']['url'] = Article::detailUrl($lift['prev']['id'],$lift['prev']['category_id'],$cate);
        }

        // 下一项
        $lift['next'] = $model->where('id','>',$id)->where('status',1)->order('id','asc')->find();
        if ($lift['next']) {
            $lift['next']['url'] = Article::detailUrl($lift['next']['id'],$lift['next']['category_id'],$cate);
        }

        return $lift;
    }
}